package thread_safe;

import threadpool.ThreadPoolFactory;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;

/**
 * CountDownLatch是通过一个计数器来实现的，计数器的初始值为线程的数量。
 * 每当一个线程完成了自己的任务后，计数器的值就会减1。
 * 当计数器值到达0时，它表示所有的线程已经完成了任务，然后在闭锁上等待的线程就可以恢复执行任务。
 */
public class CountDownLatchDemo {

    static final CountDownLatch LATCH = new CountDownLatch(10);

    public static void main(String[] args) throws InterruptedException {
        ExecutorService threadPool = ThreadPoolFactory.getThreadPool();
        long start = System.currentTimeMillis();
        for (int i = 0; i < 10; i++) {
            threadPool.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000);
                        System.out.println("check complete");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        //每当一个线程执行完任务，计数器就减1
                        LATCH.countDown();
                        System.out.println(Thread.currentThread().getName() + ": " + LATCH.getCount());
                    }
                }
            });
        }
        //主线程阻塞等待
        LATCH.await();
        long end = System.currentTimeMillis();
        System.out.println("耗时：" + (end - start) + "ms");
        System.out.println("Fire!");
        threadPool.shutdown();
    }

}
